//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using OpenLS.UI;
using OpenLS.Core.Serialization;

namespace OpenLS.Spreadsheet.UI
{
    public class RecentlyUsedDocumentManager: IXmlSerializable
    {
        private RecentlyUsedDocumentManager()
        {
            
        }
        private readonly ObservableCollection<RecentlyUsedDocument> _documents = new ObservableCollection<RecentlyUsedDocument>();
        public ObservableCollection<RecentlyUsedDocument> Documents
        {
            get
            {
                return _documents;
            }
            
        }

        public static RecentlyUsedDocumentManager Retrieved
        {
            get
            {
                if (!File.Exists(FileName))
                    return new RecentlyUsedDocumentManager();
                try{
                    using (Stream stream = File.Open(FileName, FileMode.Open))
                    {
                        var result = new RecentlyUsedDocumentManager();
                        using (XmlReader reader = new XmlTextReader(stream))
                        {
                            IXmlSerializable ss = result;
                            ss.ReadXml(reader);
                        }
                        return result;
                    }
                }catch{
                return new RecentlyUsedDocumentManager();
                }
            }
        }
        public void AddRecentlyUsedDocument(string fileName)
        {
            foreach (RecentlyUsedDocument doc in Documents)
            {
                if (doc.FullName == fileName)
                {
                    doc.Date = DateTime.Now;
                    store();
                    return;
                }
            }

            addDocument(new RecentlyUsedDocument(fileName));
           // Documents.Add(new RecentlyUsedDocument(fileName));
           /* while (Documents.Count > 40)
            {
                var l = new List<RecentlyUsedDocument>(Documents);
                l.Sort();
                Documents.Remove(l[0]);
            }*/
            store();
        }

        private void store()
        {
            
            using (Stream stream = File.Open(FileName, FileMode.Create))
            {
                using (XmlWriter writer = new XmlTextWriter(stream, Encoding.Default))
                {
                    WriteXml(writer);
                }
            }
        }
        static string FileName
        {
            get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "mru.xml"); }
        }



        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            throw new NotImplementedException();
        }


        #endregion

        #region IXmlSerializable Members

        System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
        {
            throw new NotSupportedException();
        }

        public void ReadXml(XmlReader reader)
        {
            var context = new ReadContext(reader,null);
            using (ReadContext mru = context.Read("mru"))
            {
                var docs = new List<RecentlyUsedDocument>();
                while (mru.ReaderLocalName == "document")
                    docs.Add(mru.ReadElement<RecentlyUsedDocument>());
                docs.Sort((doc1, doc2) => -DateTime.Compare(
                                              doc1.Date,
                                              doc2.Date));
                Documents.Clear();
                foreach (var doc in docs)
                {
                    addDocument(doc);
                }
            }
        }
        void addDocument (RecentlyUsedDocument doc)
        {
            Documents.Add(doc);
            while (Documents.Count > 20)
            {
                var l = new List<RecentlyUsedDocument>(Documents);
                l.Sort();
                Documents.Remove(l[0]);
            }
        }

        public void WriteXml(XmlWriter writer)
        {
            using (var context = new WriteContext("mru", null, null, writer,  null))
            {
                foreach (var document in Documents)
                {
                    context.WriteElement(document);
                }                
            }
        }

        #endregion
    }
}
